<?php defined('SYSPATH') OR die('No direct access allowed.');

class Login_Controller extends Template_Controller 
{
	public $template = 'login';
	public $content = 'login_content';

	public function __construct()
	{
		parent::__construct();
	}

	private function InitLoginView()
	{
		$this->template->title = 'Welcome to Fitness!';
	}

	public function index()
	{
		$this->InitLoginView();
		$this->login();
	}

	private function login()
	{
		$authentic = new Auth;
		if ($authentic->logged_in(''))
		{
			url::redirect('');
		}

		$this->template->content->email_address = '';
		$this->template->content->signin_error = '';

		if ($_POST)
		{
			// 加载用户
			$user = ORM::factory('user', $_POST['email_address']);
			if ( !empty($user->username) AND !empty($_POST['password']) )
			{
				if ($authentic->login($user->username, $_POST['password'], TRUE) )
				{
					if ($requested_url = Session::instance()->get('requested_url', ''))
					{
						url::redirect($requested_url);
					}
					else
					{
						url::redirect();
					}
				}
			}

			$this->template->content->email_address = $_POST['email_address'];
			$this->template->content->signin_error = '账号或密码错误，请重新输入';
		}
	}
}

